let requestUrl;
let pageList = [15, 50, 100, 200, 500];

$(document).ready(function () {

    $("#name").textbox({
        width: 150,
        required: true
    });

    $("#sort").numberspinner({
        width: 150,
        required: true
    });

    fetchServiceId();

    $("#description").textbox({
        width: 338,
        height: 100,
        required: true,
        multiline: true
    });

    /**
     * 禁止输入空格
     */
    $("#role_form input, #role_form textarea").keydown(function () {
        let event = window.event;

        if(event.keyCode === 32) {
            event.returnValue = false;
        }
    });

    $("#role_dialog").dialog({
        title: "分配权限",
        closable: true,
        closed: true,
        modal: true,
        buttons: [{
            iconCls: "icon-save",
            text: "保存",
            handler: function() {
                // 验证表单
                let result = $("#role_form").form("validate");

                if (result) {
                    // 获取表单数据
                    let data = $("#role_form").serialize();

                    ajaxPost(requestUrl, data, function (resp) {
                        $.messager.show({
                            title: "系统消息",
                            type: "slide",
                            msg: resp.message
                        });

                        $("#role_form").form("clear");
                        $("#role_dialog").dialog("close");
                        $("#role_list").datagrid("reload");
                    }, error);
                } else {
                    $.messager.alert("系统提示", "请输入正确的表单项~", "warning");
                }
            }
        }, {
            iconCls: "icon-cancel",
            text: "取消",
            handler: function() {
                $("#role_form").form("clear");
                $("#role_dialog").dialog("close");
            }
        }]
    });

    $("#role_list").datagrid({
        url: "/role/selectList",
        striped: true,
        rownumbers: true,
        fitColumns: true,
        singleSelect: true,
        selectOnCheck: false,
        toolbar: [{
            iconCls: "icon-add",
            text: "添加",
            handler: function() {
                requestUrl = "/role/insert";

                $("#role_dialog").dialog("open");
            }
        }, "-", {
            iconCls: "icon-edit",
            text: "修改",
            handler: function() {
                let rowData = $("#role_list").datagrid("getSelected");

                if (rowData) {
                    requestUrl = "/role/updateById";

                    $("#id").val(rowData.id);
                    $("#name").textbox("setValue", rowData.name);
                    $("#sort").numberspinner("setValue", rowData.sort);
                    $("#serviceId").combobox("setValue", rowData.serviceId);
                    $("#description").textbox("setValue", rowData.description);

                    $("#role_dialog").dialog("open");
                } else {
                    $.messager.alert("系统提示", "请选择要修改的记录！", "warning");
                }
            }
        }, "-", {
            iconCls: "icon-delete",
            text: "删除",
            handler: function() {
                let rows = $("#role_list").datagrid("getChecked");
                let count = rows.length;

                if (count > 0) {
                    $.messager.confirm("系统提示", "确认删除勾选的" + count + "条数据？", function (bool) {
                        if (bool) {
                            let ids = [];

                            for (let i = 0; i < rows.length; i++) {
                                ids.push(rows[i].id);
                            }

                            ajaxPost("/role/deleteByIds", {
                                ids: JSON.stringify(ids)
                            }, function (resp) {
                                $("#role_list").datagrid("reload");

                                $.messager.show({
                                    title: "系统消息",
                                    type: "slide",
                                    msg: resp.message
                                });
                            }, error);
                        }
                    });
                } else {
                    $.messager.alert("系统提示", "请选择要删除的记录！", "warning");
                }
            }
        }, "-", {
            iconCls: "icon-ok",
            text: "一键授权",
            handler: function() {
                let rowData = $("#role_list").datagrid("getSelected");

                if (rowData) {
                    let roleId = rowData.id;

                    ajaxPost("/role_permission/grant", {
                        roleId: roleId
                    }, function (resp) {
                        $.messager.show({
                            title: "系统消息",
                            type: "slide",
                            msg: resp.message
                        });
                    }, error);
                } else {
                    $.messager.alert("系统提示", "请选择一条记录！", "warning");
                }
            }
        }, "-", {
            iconCls: "icon-ok",
            text: "分配权限",
            handler: function() {
                let rowData = $("#role_list").datagrid("getSelected");

                if (rowData) {
                    let roleId = rowData.id;

                    requestUrl = "/role_permission/insert";

                    $("#roleId").val(roleId);

                    $("#permission_list").datagrid("reload", {
                        roleId: roleId
                    });

                    $("#distribute_dialog").dialog("open");
                } else {
                    $.messager.alert("系统提示", "请选择一条记录！", "warning");
                }
            }
        }],
        columns: [[
            {field: "ck", checkbox: true},
            {field: "id", title: "角色ID", hidden: true},
            {field: "name", title: "角色名", width: 100, align: "center"},
            {field: "sort", title: "排序", width: 100, align: "center"},
            {field: "description", title: "角色说明", width: 200, align: "center"},
            {field: "serviceId", title: "所属应用", width: 100, align: "center",
                formatter: function (value, rowData, rowIndex) {
                    ajaxGet("/application/selectById", {
                        id: value
                    }, function (resp) {
                        let data = resp.data;

                        $("#service_"+ rowIndex).attr({
                            "src": data.href,
                            "title": data.note
                        }).html(data.name);
                    }, error);

                    return "<a id='service_" + rowIndex + "'></a>";
                }
            }
        ]]
    });

    /******************************************************************************************************/

    $("#permissionId").combobox({
        url: "/permission/selectList",
        valueField: "id",
        textField: "name",
        width: 150,
        required: true,
        panelHeight: "auto"
    });

    $("#save").linkbutton({
        iconCls: "icon-save",
        text: "保存"
    }).on("click", function () {
        // 获取表单数据
        let result = $("#distribute_form").form("validate");

        if (result) {
            let rowData = $("#role_list").datagrid("getSelected");

            if (rowData) {
                let roleId = rowData.id;
                let permissionId = $("#permissionId").combobox("getValue");

                ajaxPost("/role_permission/insert", {
                    permissionId: permissionId,
                    roleId: roleId
                }, function (resp) {
                    $("#permission_list").datagrid("reload", {
                        roleId: roleId
                    });

                    $.messager.show({
                        title: "系统消息",
                        type: "slide",
                        msg: resp.message
                    });
                }, error);
            }
        } else {
            $.messager.alert("系统提示", "请输入正确的表单项~", "warning");
        }

    });

    $("#delete").linkbutton({
        iconCls: "icon-delete",
        text: "删除"
    }).on("click", function () {
        let row = $("#role_list").datagrid("getSelected");

        if (row) {
            let rows = $("#permission_list").datagrid("getChecked");

            if (rows.length > 0) {
                $.messager.confirm("系统提示", "确认删除选中的数据？", function (bool) {
                    if (bool) {
                        let roleId = row.id;
                        let permissionIds = [];

                        for (let i = 0; i < rows.length; i++) {
                            permissionIds.push(rows[i].id);
                        }

                        ajaxPost("/role_permission/delete", {
                            permissionIds: JSON.stringify(permissionIds),
                            roleId: roleId
                        }, function (resp) {
                            // 重新加载表格数据
                            $("#permission_list").datagrid("reload", {
                                roleId: roleId
                            });

                            $.messager.show({
                                title: "系统消息",
                                type: "slide",
                                msg: resp.message
                            });
                        }, error);
                    }
                });
            } else {
                $.messager.alert("系统提示", "请选择要删除的记录！", "warning");
            }
        }
    });

    $("#cancel").linkbutton({
        iconCls: "icon-cancel",
        text: "取消"
    }).click(function () {
        // 清空表单
        $("#distribute_form").form("clear");
    });

    $("#permission_list").datagrid({
        url: "/role_permission/selectByPage",
        width: 1200,
        height: 550,
        striped: true,
        fitColumns: true,
        rownumbers: true,
        singleSelect: true,
        selectOnCheck: false,
        pagination: true,
        pageList: pageList,
        pageSize: pageList[0],
        columns: [[
            {field: "ck", checkbox: true},
            {field: "name", title: "权限名", width: 150, align: "center"},
            {field: "url", title: "请求路径", width: 150, align: "center"},
            {field: "parentId", title: "父级权限", width: 100, align: "center",
                formatter: function (value, rowData, rowIndex) {
                    if (value) {
                        ajaxGet("/permission/selectById", {
                            id: value
                        }, function (resp) {
                            let data = resp.data;

                            $("#parent_" + rowIndex).html(data.name);
                        }, error);

                        return "<div id='parent_" + rowIndex + "'></div>";
                    }

                    return "/";
                }
            },
            {field: "serviceId", title: "所属应用", width: 100, align: "center",
                formatter: function (value, rowData, rowIndex) {
                    ajaxGet("/application/selectById", {
                        id: value
                    }, function (resp) {
                        let data = resp.data;

                        $("#application_"+ rowIndex).attr({
                            "src": data.href,
                            "title": data.note
                        }).html(data.name);
                    }, error);

                    return "<a id='application_" + rowIndex + "'></a>";
                }
            }
        ]]
    });

    $("#distribute_dialog").dialog({
        title: "分配权限",
        closable: true,
        closed: true,
        modal: true
    });

});